package com.saver.modules.sys.service;

import com.saver.common.utils.R;
import com.saver.modules.sys.dao.SysParamDao;
import com.saver.modules.sys.dao.SysUserTokenDao;
import com.saver.modules.sys.entity.SysParamEntity;
import com.saver.modules.sys.entity.SysUserTokenEntity;
import com.saver.modules.sys.oauth2.TokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;


/**
 * 系统token
 *
 * @author yuxiaolong
 * @email 1005471232@qq.com
 * @date 2018年08月30日 下午10:45
 */
@Service("sysUserTokenService")
public class SysUserTokenService {

    private final static String TOKEN_EXPIRE_TIME = "TOKEN_EXPIRE_TIME";

    @Autowired
    private SysUserTokenDao sysUserTokenDao;

    @Autowired
    private SysParamDao sysParamDao;

    @Transactional
    public R createToken(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        SysParamEntity token_expire_time = sysParamDao.findByParamName(TOKEN_EXPIRE_TIME);
        int i = Integer.parseInt(token_expire_time.getParamValue());
        Date expireTime = new Date(now.getTime() + i * 1000);

        SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        tokenEntity.setUpdateTime(now);
        tokenEntity.setExpireTime(expireTime);
        //保存token
        sysUserTokenDao.save(tokenEntity);

        R r = R.ok().put("token", token).put("expire", i);
        return r;
    }
    

    @Transactional
    public void logout(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        Optional<SysUserTokenEntity> byId = sysUserTokenDao.findById(userId);
        SysUserTokenEntity tokenEntity = byId.get();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        sysUserTokenDao.save(tokenEntity);
    }
}
